import json
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

# 京东商城网址
url = 'https://www.jd.com/'
driver = webdriver.Chrome()
# 浏览器访问地址
driver.get(url)
# 隐式等待，确保动态内容节点被完全加载出来——时间感受不到
driver.implicitly_wait(3)
# 最大化浏览器窗口，主要是防止内容被遮挡
driver.maximize_window()

# 找到并点击“请登录”按钮
login_button = driver.find_element(By.CSS_SELECTOR, 'a.link-login')
login_button.click()
# 等待账号和密码输入框加载完成
wait = WebDriverWait(driver, 10)
username_input = wait.until(EC.presence_of_element_located((By.NAME, 'loginname')))
password_input = driver.find_element(By.NAME, 'nloginpwd')

# 输入账号和密码
username_input.send_keys('13759638977')
password_input.send_keys('cc13759638977')

# 找到并点击登录按钮
login_submit = driver.find_element(By.ID, 'loginsubmit')
login_submit.click()

sleep(20)

# 登陆后
after_login = driver.get_cookies()

# 获取 cookies
cookies = driver.get_cookies()
# 将 cookies 写入文件
with open("cookies.txt", "w") as f:
    json.dump(cookies, f)
driver.quit()
